﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using Cesave.DistributedServices.PermisosModule.WindowsHost.Resources;
using Cesave.Domain.Core.Entities;
using Cesave.Domain.PermisosModule.Contracts.Juntas;
using Cesave.Domain.PermisosModule.Entities;
using Cesave.Infrastructure.CrossCutting.IoC;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Juntas
{
	public partial class JuntasViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Junta> _juntas;

		/// <summary>
		/// 
		/// </summary>
		private Junta _junta;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Junta> Juntas
		{
			get
			{
				return _juntas;
			}
			private set
			{
				_juntas = value;
				if (_juntas != null)
					RaisePropertyChanged("Juntas");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Junta Junta
		{
			get
			{
				return _junta;
			}
			private set
			{
				_junta = value;
				if (_junta != null)
					RaisePropertyChanged("Junta");
				else
					_juntasView.switchStatusButton.Enabled = false;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool IsJuntaReady
		{
			get
			{
				return Junta != null;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool IsJuntaActive
		{
			get
			{
				if (Junta != null)
					return Junta.Status;
				else
					return false;
			}
		}

		#endregion

		#region Actions

		/// <summary>
		/// 
		/// </summary>
		private void LoadJuntas()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IJuntaService juntaService = IoCFactory.Resolve<IJuntaService>();
					e.Result = juntaService.FindJuntasByEstado(Estado.EstadoGuid);
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Juntas = e.Result as List<Junta>;
					else if (e.Error != null)
						MessageBox.Show(
							_juntasView,
							e.Error.Message,
							WindowTitles.JuntasWindowTitle,
							MessageBoxButtons.OK,
							MessageBoxIcon.Error
						);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void AddNewJunta(object sender, EventArgs e)
		{
			_juntasView.juntasBindingSource.AddingNew += AddingNewJunta;
			_juntasView.juntasBindingSource.AddNew();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void AddingNewJunta(object sender, AddingNewEventArgs e)
		{
			Junta = new Junta
			{
				DistritoGuid = Distrito.DistritoGuid,
				DistritoId = Distrito.DistritoId,
				EstadoGuid = Estado.EstadoGuid,
				EstadoId = Estado.EstadoId,
				Domicilio = string.Empty,
				Email = string.Empty,
				JuntaGuid = Guid.NewGuid(),
				JuntaId = 0,
				MunicipioGuid = Municipio.MunicipioGuid,
				MunicipioId = Municipio.MunicipioId,
				Nombre = string.Empty,
				NombreCorto = string.Empty,
				RFC = string.Empty,
				Status = true,
				Telefono = string.Empty,
			};
			Junta.MarkAsAdded();
			e.NewObject = Junta;
			FocusDefaultControl();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SaveJunta(object sender, EventArgs e)
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (wSender, wArgs) =>
				{
					IJuntaService juntaService = IoCFactory.Resolve<IJuntaService>();
					if (Junta.ChangeTracker.State == ObjectState.Added)
						juntaService.AddJunta(Junta);
					else
						juntaService.ChangeJunta(Junta);
					Junta.AcceptChanges();
				};
				worker.RunWorkerCompleted += (wSender, wArgs) =>
				{
					EndWaiting();
					if (!wArgs.Cancelled && wArgs.Error == null)
						SetCurrentJunta(_juntasView.juntasBindingSource, e);
					else if (wArgs.Error != null)
						MessageBox.Show(
							_juntasView,
							wArgs.Error.Message,
							WindowTitles.JuntasWindowTitle,
							MessageBoxButtons.OK,
							MessageBoxIcon.Error
						);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void DeleteJunta(object sender, EventArgs e)
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (wSender, wArgs) =>
				{
					IJuntaService juntaService = IoCFactory.Resolve<IJuntaService>();
					Junta.MarkAsDeleted();
					juntaService.DeleteJunta(Junta);
					Junta.AcceptChanges();
				};
				worker.RunWorkerCompleted += (wSender, wArgs) =>
				{
					EndWaiting();
					if (!wArgs.Cancelled && wArgs.Error == null)
						_juntasView.juntasBindingSource.RemoveCurrent();
					else if (wArgs.Error != null)
						MessageBox.Show(
							_juntasView,
							wArgs.Error.Message,
							WindowTitles.JuntasWindowTitle,
							MessageBoxButtons.OK,
							MessageBoxIcon.Error
						);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Activate(object sender, EventArgs e)
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (wSender, wArgs) =>
				{
					IJuntaService juntaService = IoCFactory.Resolve<IJuntaService>();
					juntaService.ActivateJunta(Junta);
					Junta.AcceptChanges();
				};
				worker.RunWorkerCompleted += (wSender, wArgs) =>
				{
					EndWaiting();
					if (!wArgs.Cancelled && wArgs.Error == null)
						SetCurrentJunta(_juntasView.juntasBindingSource, e);
					else if (wArgs.Error != null)
						MessageBox.Show(
							_juntasView,
							wArgs.Error.Message,
							WindowTitles.JuntasWindowTitle,
							MessageBoxButtons.OK,
							MessageBoxIcon.Error
						);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Deactivate(object sender, EventArgs e)
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (wSender, wArgs) =>
				{
					IJuntaService juntaService = IoCFactory.Resolve<IJuntaService>();
					juntaService.DeactivateJunta(Junta);
					Junta.AcceptChanges();
				};
				worker.RunWorkerCompleted += (wSender, wArgs) =>
				{
					EndWaiting();
					if (!wArgs.Cancelled && wArgs.Error == null)
						SetCurrentJunta(_juntasView.juntasBindingSource, e);
					else if (wArgs.Error != null)
						MessageBox.Show(
							_juntasView,
							wArgs.Error.Message,
							WindowTitles.JuntasWindowTitle,
							MessageBoxButtons.OK,
							MessageBoxIcon.Error
						);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methdos

		/// <summary>
		/// 
		/// </summary>
		private void OnJuntasPropertyChanged()
		{
			_juntasView.bindingNavigatorDeleteItem.Enabled = _juntasView.saveButton.Enabled = _juntasView.juntaBindingNavigatorSaveItem.Enabled = Juntas.Count > 0;
			_juntasView.juntasBindingSource.DataSource = Juntas;
			_juntasView.juntasBindingSource.CurrentChanged += SetCurrentJunta;
			SetCurrentJunta(_juntasView.juntasBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentJunta(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null)
				if (bindingSource.Current != null)
					Junta = bindingSource.Current as Junta;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnJuntaPropertyChanged()
		{
			_juntasView.switchStatusButton.Enabled = _juntasView.saveButton.Enabled = _juntasView.juntaBindingNavigatorSaveItem.Enabled = IsJuntaReady;
			if (IsJuntaActive)
				SetDeactivate();
			else
				SetActivate();
			_juntasView.distritoComboBox.SelectedValue = Junta.DistritoGuid;
			_juntasView.municipioGuidComboBox.SelectedValue = Junta.MunicipioGuid;
			/// TODO: Cargar las entidades dependientes de
			///		  la junta.
		}

		/// <summary>
		/// 
		/// </summary>
		private void SetDeactivate()
		{
			_juntasView.switchStatusButton.Text = "&Desactivar";
			_juntasView.switchStatusButton.Image = Properties.Resources.delete;
			_juntasView.switchStatusButton.Click += Deactivate;
		}

		/// <summary>
		/// 
		/// </summary>
		private void SetActivate()
		{
			_juntasView.switchStatusButton.Text = "&Activar";
			_juntasView.switchStatusButton.Image = Properties.Resources.check;
			_juntasView.switchStatusButton.Click += Activate;
		}

		#endregion

	}
}
